package atomic;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 验证i++的非原子性
 * @author lcx
 *
 */
public class AtomicIntegerTest {
	static AtomicInteger i=new AtomicInteger(0); 
	public static void main(String[] args) {
		//1
		while(true)
		{
			//
			CountDownLatch latch=new CountDownLatch(2);
			IncrementThread td1=new IncrementThread(latch);
			IncrementThread td2=new IncrementThread(latch);
			td1.start();
			td2.start();
			try {
				latch.await();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			System.out.println("i="+i);
		}
	}

}

class IncrementThread extends Thread
{
	CountDownLatch latch;
	public IncrementThread(CountDownLatch latch)
	{
		this.latch=latch;
	}
	public void run()
	{
			for(int num=0;num<5000;num++)
				AtomicIntegerTest.i.getAndIncrement();
			latch.countDown();
		}
}